<template>
  <el-dialog v-model="isShowDialog" :width="1000" @opened="handleDialogOpened" title="编辑规格">
    <el-form :label-width="100" v-loading="loading">
      <el-form-item label="商品规格" prop="products">
        <el-row class="form-inline-row">
          <el-form-item>
            <el-select @change="selectProduct" placeholder="请选择规格" clearable>
              <el-option v-for="(item) in productsOptions" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-table :data="productList">
          <el-table-column label="规格名称" prop="name" min-width="120">
            <template #header>
              <span style="color: red">* </span>规格名称
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.name" placeholder="请输入规格名称"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="规格图片" prop="thumbnailUrl" width="180">
            <template #header>
              <span style="color: red">* </span>规格图片
            </template>
            <template #default="scope">
              <upload v-model:model-value="scope.row.thumbnailUrl" list-type="picture-card" :limit="1">
                <template #default>
                  <el-icon>
                    <plus/>
                  </el-icon>
                </template>
              </upload>
            </template>
          </el-table-column>
          <el-table-column label="市场价格" prop="originalPrice" min-width="100"></el-table-column>
          <el-table-column label="售价" prop="combinedPrice" width="350">
            <template #header>
              <span style="color: red">* </span>售价
            </template>
            <template #default="scope">
              <div style="display: flex;flex-wrap: nowrap;">
                <el-input v-model="scope.row.payOfCurrencyCount" type="number">
                  <template #append>
                    积分
                  </template>
                </el-input>
                <div style="width: 10px"></div>
                <el-input v-model="scope.row.payPrice" type="number">
                  <template #append>
                    元
                  </template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="可售库存" prop="stock" min-width="100"></el-table-column>
          <el-table-column label="预占库存" prop="beforeStock" min-width="100"></el-table-column>
          <el-table-column label="库存增减" prop="addOrDeductionStockCount" min-width="230">
            <template #header>
              <span style="color: red">* </span>库存增减
            </template>
            <template #default="scope">
              <el-input v-model="scope.row.addOrDeductionStockCount" type="number" placeholder="请输入增减量（如：-20）"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="saveRow(scope.row, scope.$index)">保存</el-button>
              <el-button link type="primary" @click="switchStatus(scope.row, scope.$index)"
                         v-if="scope.row.onlineStatus">下线
              </el-button>
              <el-button link type="primary" @click="switchStatus(scope.row, scope.$index)"
                         v-else="scope.row.onlineStatus">上线
              </el-button>
              <el-button link type="danger" @click="_deleteProduct(scope.row, scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="总库存">
        {{ totalStock }}
      </el-form-item>

      <el-form-item label="剩余库存">
        {{ stock }}
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ComputedRef, Ref} from "vue";
import {ElMessage} from "element-plus";
import {deleteProduct, getGoodsProducts, getStoreGoodsDetail, saveProduct, switchProductStatus} from "@/api/pointsMall";
import {IStoreGoodsDetail, IStoreProductRow} from "@/api/modules/pointsMall";
import {useMallConfig} from "@/views/pointsMall/compositions/useMallConfig";

const props = defineProps<{
  show: boolean,
  rowData: any,
}>()
const emits = defineEmits(['update:show'])
const loading = ref(false)

const isShowDialog = computed({
  get() {
    return props.show
  },
  set(val) {
    emits('update:show', val)
  }
})

const {mallConfig} = useMallConfig()

const totalStock = computed(() => {
  return productList.value.reduce((total, current) => total + current.totalStock, 0)
})

const stock = computed(() => {
  return productList.value.reduce((total, current) => total + current.stock, 0)
})

// 删除规格行
const _deleteProduct = async (row: IStoreProductRow, index: number) => {
  if (row.id) { // 数据库中的数据
    const rs = await deleteProduct({id: row.id})

    if (rs.code === 200) {
      ElMessage.success('删除成功')
      _getSpecificationList()
    }
  } else { // 添加后未保存的数据行
    productList.value.splice(index, 1)
  }
}

// 切换上下线状态
const switchStatus = async (row: IStoreProductRow, index: number) => {
  if (row.id) {
    const rs = await switchProductStatus({ id: row.id, name: row.name }) // 上下线

    if (rs.code === 200) {
      ElMessage.success('切换成功')
      _getSpecificationList()
    }
  } else {
    ElMessage.warning('切换状态失败：商品未保存')
  }
}

const productList: Ref<IStoreProductRow[]> = ref<IStoreProductRow[]>([])
// 获取该商品的规格
const _getSpecificationList = async () => {
  const rs = await getGoodsProducts({id: props.rowData.id})

  if (rs.code === 200) {
    productList.value = (rs.payload ?? []).map(product => ({
      ...product,
      beforeStock: productsOptions.value.find(storeProduct => storeProduct.id === product.storeProductId)?.beforeStock ?? 0,
      payPrice: product.payPrice && !isNaN(product.payPrice) ? product.payPrice / 100 : 0
    }))
  }
}

const storeGoodsDetail = ref<IStoreGoodsDetail>()
// 可选商品规格选项
const productsOptions = ref<IStoreProductRow[]>([])
// 获取商家的可选商品规格
const _getStoreGoodsDetail = async () => {
  const rs = await getStoreGoodsDetail({id: props.rowData.storeGoodsId})

  if (rs.code === 200) {
    if (rs.payload) {
      storeGoodsDetail.value = rs.payload
      productsOptions.value = rs.payload.products.map(item => ({
        ...item,
        thumbnailUrl: item.thumbnailUrl ?? '', // upload组件需要
        addOrDeductionStockCount: 0, // 库存增减量
      }))
    }
  }
}

// 选择后添加规格行
const selectProduct = (val: string) => {
  const target = productsOptions.value.find(item => item.id === val)
  if (target) {
    let _rowItem = {...target}
    _rowItem.mallId = mallConfig.value.id
    _rowItem.goodsId = props.rowData.id
    _rowItem.storeGoodsId = storeGoodsDetail.value?.id
    _rowItem.storeProductId = target.id
    _rowItem.id = null // 后端视id存在与否区别编辑和新增
    _rowItem.stock = 0
    productList.value.push(_rowItem)
  }

  // console.log(productList.value)
}

const isEmpty = (val: any) => {
  return val === undefined || val === null || val === ''
}

const isNegative = (val: number) => {
  return val < 0
}

const createErrorMessage = (result: boolean, message: string) => {
  return {
    result,
    message,
  }
}

const checkRowData = (rowData: IStoreProductRow) => {
  if (isEmpty(rowData.name)) {
    return createErrorMessage(false, `请输入规格名称`)
  }

  if (isEmpty(rowData.thumbnailUrl)) {
    return createErrorMessage(false, `请上传规格图片`)
  }

  if (isEmpty(rowData.payOfCurrencyCount)) {
    return createErrorMessage(false, `请输入售价（积分）`)
  }

  if (isNegative(rowData.payOfCurrencyCount)) {
    return createErrorMessage(false, `售价（积分）不能为负数`)
  }

  if (isEmpty(rowData.payPrice)) {
    return createErrorMessage(false, `请输入售价（现金）`)
  }

  if (isNegative(rowData.payPrice)) {
    return createErrorMessage(false, `售价（现金）不能为负数`)
  }

  if (rowData.addOrDeductionStockCount > rowData.beforeStock) {
    return createErrorMessage(false, `库存增减不能大于预占库存`)
  }

  return createErrorMessage(true, '')
}

const formatData = (row: IStoreProductRow) => {
  const _row = {...row}
  _row.addOrDeductionStockCount = isEmpty(_row.addOrDeductionStockCount) || isNaN(_row.addOrDeductionStockCount)
      ? 0
      : Number(_row.addOrDeductionStockCount)
  return _row
}

const saveRow = async (row: IStoreProductRow, index: number) => {
  const checkResult = checkRowData(row)
  if (!checkResult.result) {
    ElMessage.error(checkResult.message)
    return
  }

  const _row = formatData(row)

  const rs = await saveProduct(_row)

  if (rs.code === 200) {
    ElMessage.success('保存成功')
    _getSpecificationList()
  }
}

const cancel = () => {
  isShowDialog.value = false
}

const handleDialogOpened = async () => {
  loading.value = true
  await _getStoreGoodsDetail()
  await _getSpecificationList()
  loading.value = false
}

</script>

<style scoped lang="scss">
.form-inline-row {
  margin-bottom: 5px;
}
</style>
